import { OAuth2Client } from 'google-auth-library';
import axios from 'axios';

// Google OAuth配置
export const GOOGLE_CONFIG = {
  // Google Client ID，从环境变量获取
  clientId: process.env.GOOGLE_CLIENT_ID || '',
  // Google Client Secret，从环境变量获取
  clientSecret: process.env.GOOGLE_CLIENT_SECRET || '',
  // 重定向URI
  redirectUri: process.env.GOOGLE_REDIRECT_URI || 'http://localhost:3000/google-callback',
};

// 创建Google OAuth客户端
export const googleClient = new OAuth2Client(
  GOOGLE_CONFIG.clientId,
  GOOGLE_CONFIG.clientSecret,
  GOOGLE_CONFIG.redirectUri
);

/**
 * 验证Google ID Token
 * @param token Google ID Token
 * @returns 验证后的Google用户信息
 */
export const verifyGoogleToken = async (token: string) => {
  try {
    const ticket = await googleClient.verifyIdToken({
      idToken: token,
      audience: GOOGLE_CONFIG.clientId,
    });
    
    const payload = ticket.getPayload();
    
    if (!payload) {
      throw new Error('无效的Google令牌');
    }
    
    // 验证token的发行者
    if (payload.iss !== 'accounts.google.com' && payload.iss !== 'https://accounts.google.com') {
      throw new Error('无效的token发行者');
    }
    
    // 验证audience
    if (payload.aud !== GOOGLE_CONFIG.clientId) {
      throw new Error('无效的audience');
    }
    
    return {
      googleId: payload.sub,
      email: payload.email,
      name: payload.name,
      picture: payload.picture,
      emailVerified: payload.email_verified,
      givenName: payload.given_name,
      familyName: payload.family_name,
    };
  } catch (error) {
    console.error('Google token验证失败:', error);
    if (error instanceof Error) {
      throw new Error(`Google令牌验证失败: ${error.message}`);
    }
    throw new Error('Google令牌验证失败');
  }
};

/**
 * 使用授权码获取Google用户信息
 * @param code Google授权码
 * @returns Google用户信息
 */
export const verifyGoogleCode = async (code: string) => {
  try {
    // 使用授权码换取访问令牌
    const { tokens } = await googleClient.getToken(code);
    
    if (!tokens.access_token) {
      throw new Error('无法获取访问令牌');
    }
    
    // 使用访问令牌获取用户信息
    const response = await axios.get('https://www.googleapis.com/oauth2/v2/userinfo', {
      headers: {
        Authorization: `Bearer ${tokens.access_token}`,
      },
    });
    
    const userInfo = response.data;
    
    return {
      googleId: userInfo.id,
      email: userInfo.email,
      name: userInfo.name,
      picture: userInfo.picture,
      emailVerified: userInfo.verified_email,
      givenName: userInfo.given_name,
      familyName: userInfo.family_name,
    };
  } catch (error) {
    console.error('Google授权码验证失败:', error);
    if (error instanceof Error) {
      throw new Error(`Google授权码验证失败: ${error.message}`);
    }
    throw new Error('Google授权码验证失败');
  }
};

/**
 * 检查Google OAuth配置是否完整
 */
export const isGoogleConfigured = (): boolean => {
  return !!(GOOGLE_CONFIG.clientId && GOOGLE_CONFIG.clientSecret);
};